package com.topnav.mc.admin.security.jwt.handle;

import com.alibaba.fastjson2.JSON;
import com.topnav.mc.exception.ExceptionMsg;
import com.topnav.mc.uitls.ErrorResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 说明： 自定义无权访问处理类
 * @类名: Role
 * <p>
 *
 * </p>
 * @author   kenny
 * @Date	 2022年2月9日下午5:26:18
 */
@Component
@Slf4j
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {

    	log.error(e.getMessage());
    	log.error(ExceptionMsg.ERROR_AUTHENTICATION_ACCESS_DENIED.getDesc());
        String json =  JSON.toJSONString(
        		ErrorResultUtil.result(ExceptionMsg.ERROR_AUTHENTICATION_ACCESS_DENIED));
        // 允许跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 允许自定义请求头token(允许head跨域)
        response.setHeader("Access-Control-Allow-Headers", "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");

        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(json);
    }
}
